﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mangix.Core.Caching;
using Mangix.Core.Data;
using Mangix.Core.Librs;
using Mangix.Mapping.SysPermission;
using Mangix.Mapping;
using Mangix.Services.Category;
using System.Data.Entity;

namespace Mangix.Services.SysPermission
{
    public class PermissionRecordService : ISysPermissionService
    {
        private const string MODEL_KEY = "Mangix.admin.permission_all";
        private ICacheManager _cacheManager;
        private IRepository<Entities.SysPermission> _sysPermissionRepository;
        private ICategoryService _categoryService;

        public PermissionRecordService(ICacheManager cacheManager,
            IRepository<Entities.SysPermission> sysPermissionRepository,
            ICategoryService categoryService)
        {
            this._cacheManager = cacheManager;
            this._sysPermissionRepository = sysPermissionRepository;
            this._categoryService = categoryService;
        }

        /// <summary>
        /// 获取所有的数据并缓存，不存在返回null
        /// </summary>
        /// <returns></returns>
        public IEnumerable<PermissionRecordMapping> getAllPermissionRecordes()
        {
            return _cacheManager.get<List<PermissionRecordMapping>>(MODEL_KEY, () =>
           {
               var list = _sysPermissionRepository.Table.ToList();
               if (list.Any())
                   return list.Select(x => x.toModel()).ToList();
               return null;
           });
        }

        /// <summary>
        ///  通过roleid获取
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public IEnumerable<PermissionRecordMapping> getByRoleId(Guid roleId)
        {
            var list = getAllPermissionRecordes();
            if (list != null && list.Any())
                return list.Where(o => o.RoleId == roleId).ToList();
            return null;
        }

        /// <summary>
        /// 通过roleids获取
        /// </summary>
        /// <param name="roleIds"></param>
        /// <returns></returns>
        public IEnumerable<PermissionRecordMapping> getByRoleIds(IEnumerable<Guid> roleIds)
        {
            var list = getAllPermissionRecordes();
            if (list != null && list.Any())
                return list.Where(o => roleIds.Contains(o.RoleId)).ToList();
            return null;
        }

        /// <summary>
        /// 保存设置角色的权限数据
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="categoryIds">categoryIds</param>
        public void SavePermissionRecord(Guid roleId, IEnumerable<int> categoryIds, Guid creator)
        {
            var list = _sysPermissionRepository.Table.Where(o => o.RoleId == roleId);
            if (categoryIds == null || !categoryIds.Any())
                foreach (var del in list)
                    _sysPermissionRepository.Entities.Remove(del);
            else
            {
                foreach (int categoryId in categoryIds)
                {
                    var item = list.FirstOrDefault(o => o.CategoryId == categoryId);
                    if (item == null)
                    {
                        _sysPermissionRepository.Entities.Add(new Entities.SysPermission()
                        {
                            Id = Guid.NewGuid(),
                            RoleId = roleId,
                            CreationTime = DateTime.Now,
                            Creator = creator,
                            CategoryId = categoryId
                        });
                    }
                }
                foreach (var del in list)
                    if (!categoryIds.Any(o => o == del.CategoryId))
                        _sysPermissionRepository.Entities.Remove(del);
            }
            _sysPermissionRepository.DbContext.SaveChanges();
            _cacheManager.remove(MODEL_KEY);
        }
    }
}
